import express from "express";
import * as fs from "node:fs";
import {LoggerFactory} from "../logs/Logger";

const log = LoggerFactory.getLogger('FileService');
const fileRoute = express.Router();

fileRoute.get('/download/:filepath', (req, res) => {
    const filepath = decodeURIComponent(req.params.filepath)
    log.info(`下载文件路径： ${filepath}`)
    res.setHeader("Content-Type", "application/octet-stream")
    res.setHeader("Content-Disposition", "application/octet-stream")
    fs.stat(filepath, (err, stats) => {
        if (err) {
            log.error(`下载出错：error=${err.message}`, err)
            res.status(404)
            return
        }
        res.setHeader("Content-Length", stats.size)
        const fileStream = fs.createReadStream(filepath)
        fileStream.pipe(res)
    })

})

export default fileRoute